//
// Created by wuzhe on 2022/3/30.
//

#include <sstream>
#include <algorithm>
#include <utility>
#include "Room.hh"
#include "Player.hh"

Room::Room(Space *space, std::string roomName, Player *player, int id):space(space),roomName(roomName),roomId(id),owner(player) {
    onCreate();
}

Room::~Room() {
    onDelete();
}

void Room::broadcast(Msg msg) {
    for (auto& [a, b] : playerMap) {
        b->doBroadcast(msg);
    }
}

void Room::onPlayerEnter(Player* player) {
    player->currentRoom = this;
//    this->playerMap = std::unordered_map<std::string, Player*> ();
    playerMap[player->IP] = player;
    std::stringstream sstream;
    sstream << "room[" << roomName << "]:" << "Player\"" << player->getRoleName() << "\" enter.";
    INFO(sstream.str());
}

void Room::onPlayerQuit(Player* player) {
    this->playerMap.erase(player->IP);
    std::stringstream sstream;
    sstream << "room[" << roomName << "]:" << "Player\"" << player->getRoleName() << "\" quit.";
    INFO(sstream.str());
}

void Room::onCreate() {
    std::stringstream ss;
    ss << "create room [" << roomName << "]";
    INFO(ss.str());
}

void Room::onDelete() {

}

void Room::onTalk(std::string msg, Player& player) {
    std::stringstream ss;
    ss << "[" << roomName << "]" << "[" << player.getRoleName() << "]" << msg;
    INFO(ss.str());
    Msg m(msg, player.getRoleName(), JJ::Utils::getCurrentTime());
    space->recordMsg(this, m);
    if (msgQueue.size() == 10) {
        msgQueue.pop_back();
    }
    msgQueue.push_front(m.toString());
    broadcast(m);
}

const std::deque<std::string>& Room::getHistory() const {
    return msgQueue;
}

void Room::initHistory(int count) {
    space->initRoomHistory(this, count);
}


